import { BrowserWindow, app, shell } from 'electron';
import icon from '../../resources/icon.png?asset'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'

let notesWin = null;

const createnotesWin = () => {
    notesWin = new BrowserWindow({
        title: 'Yangshao Notes',
        width: 1280,
        height: 720,
        autoHideMenuBar: true,
        icon: icon,
        webPreferences: {
            nodeIntegration: true,
            preload: join(__dirname, '../preload/index.js'),
        },
        resizable: true,
        show:false

    });
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
        notesWin.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
        notesWin.loadFile(join(__dirname, '../renderer/index.html'))
    }
    // 假设你想在创建窗口后立即打开设置路由
    notesWin.webContents.on('did-finish-load', () => {
        notesWin.webContents.send('set-route', '/noteInfo');
    });

    notesWin.webContents.setWindowOpenHandler((details) => {
        if (url.startsWith('https:')) shell.openExternal(url);
        return { action: 'deny' }
    })

    return notesWin;
}
function closenotesWin() {
    if (notesWin && !notesWin?.isDestroyed()) {
        notesWin?.close();
    }
    notesWin = null;
}

function opennotesWin() {
    if (!notesWin || notesWin?.isDestroyed()) {
        notesWin = createnotesWin();
    }
}
function shownotesWin(){
    notesWin?.show();
}
function hidenotesWin() {
    notesWin.hide();
}
// 写一个show和hide切换
function showHidenotesWin() {
    notesWin.isVisible() ? notesWin.hide() : notesWin.show();
}
function goHomenotesWin() {
    notesWin.loadURL('http://localhost:3456/notes')
}

function minimizenotesWin() {
    notesWin.minimize();
}

function focusnotesWin() {
    if (!notesWin || notesWin?.isDestroyed()) {
        notesWin = createnotesWin();
    } else {
        // Focus on the main window if the user tried to open another
        if (notesWin.isMinimized()) notesWin.restore();
        if (!notesWin.isVisible()) notesWin.show();
        notesWin.focus();
    }
}

function sendEuUpdateCanAvailable(arg, update) {
    if (notesWin && !notesWin?.isDestroyed()) {
        notesWin.webContents.send('eu:update-can-available', {
            update: update,
            version: app.getVersion(),
            newVersion: arg?.version,
        });
    }
}

export {
    closenotesWin,
    createnotesWin,
    shownotesWin,
    focusnotesWin,
    hidenotesWin,
    minimizenotesWin,
    opennotesWin,
    sendEuUpdateCanAvailable,
    showHidenotesWin,
    goHomenotesWin
};